package com.bawei.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.bawei.dao.UserDao;
import com.bawei.pojo.User;
import com.bawei.service.UserService;
import com.bawei.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public int regis(User user) {
        try {
            String encryptedPwd = MD5Util.getEncryptedPwd(user.getPassword());
            user.setPassword(encryptedPwd);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return userDao.regis(user);
    }

    @Override
    public int login(User user) {
        User userEntity = userDao.getUser(user.getUserName());
        if (userEntity!=null){
            try {
                if (MD5Util.validPassword(user.getPassword(),userEntity.getPassword())){
                    ValueOperations<String, String> ops = redisTemplate.opsForValue();
                    ops.set("user", JSONObject.toJSONString(userEntity));
                    return 1;
                }else {
                    return 2;
                }
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return 0;
    }

    @Override
    public User findUserName(String userName) {
        return userDao.findUserName(userName);
    }
}
